#include "StdAfx.h"
#include "ProxyManager.h"
#include "rapidxml/rapidxml.hpp"
#include "rapidxml/rapidxml_print.hpp"
#include "rapidxml/rapidxml_utils.hpp"

using namespace rapidxml;

CProxyManager::CProxyManager(void)
{
	InitializeCriticalSection(&m_csProxyList);
}


CProxyManager::~CProxyManager(void)
{
}

VOID CProxyManager::LoadProxyList(CString strFilepath)
{
	USES_CONVERSION;
	try
	{
		m_lstProxy.RemoveAll();
		file<> fdoc(W2A(strFilepath));
		xml_document<> doc;
		doc.parse<0>(fdoc.data());

		xml_node<>* root = doc.first_node();
		if(root != NULL && 
			stricmp(root->name(), "proxy_list") == 0)
		{
			// We get the root, then traverse it
			xml_node<>* nodeProxy = root->first_node("proxy");
			while(nodeProxy != NULL)
			{
				xml_node<>* nodeProxyIP = nodeProxy->first_node("proxy_ip");
				xml_node<>* nodeProxyPort = nodeProxy->first_node("proxy_port");
				if(nodeProxyIP != NULL && nodeProxyPort != NULL)
				{
					CProxyItem proxy(nodeProxyIP->value(), nodeProxyPort->value());
					m_lstProxy.AddTail(proxy);
				}
				nodeProxy = nodeProxy->next_sibling("proxy");
			}
		}
	}
	catch(std::exception ex)
	{
		return;
	}
}


CProxyItem* CProxyManager::GetRandomProxy(BOOL bAllowNullProxy)
{
	CProxyItem* ret = NULL;
	EnterCriticalSection(&m_csProxyList);

	int nCount = m_lstProxy.GetCount();
	if(bAllowNullProxy)
	{
		++nCount;
	}
	
	int nIndex = rand() % nCount;
	if(bAllowNullProxy && nIndex == nCount - 1)
	{
		ret = NULL;
	}
	else
	{
		POSITION pos = m_lstProxy.FindIndex(nIndex);
		ret = &m_lstProxy.GetAt(pos);
	}
	
	LeaveCriticalSection(&m_csProxyList);

	return ret;
}
